# set working directory
setwd('~/replication_files')

# function to load and install packages
load_packages<-function(packages){
  sapply(packages,function(x){
    f<-require(x,character.only=T)
    if(!f) install.packages(x); f<-require(x,character.only=T)
    return(f)},USE.NAMES=T)
}

# load packages
load_packages(c('data.table'))

# read in data
(FinDT<-readRDS('TablesA4A5.rds'))

## Table A4

# get number of searches that led to vaccine non-skeptical websites
ProVaxSearches<-FinDT[code==0,list(search_term,N)]
# order from most hits to least
setorder(ProVaxSearches,-N)
# keep top 53
(ProVaxSearches<-ProVaxSearches[1:53])
ProVaxSearches[,search_term:=gsub('%2c',',',search_term,fixed=T)]

# convert to Latex table
(tabMain<-apply(ProVaxSearches,1,function(x) paste(x,collapse=' & ')))
(tabMain<-paste0(tabMain,' \\\\'))

# top of latex table
tabTop<-c('\\begin{table}[!p]',
           '\\begin{scriptsize}',
           '\\caption{Top Google searches immediately prior to exposure to non-skeptical vaccine webpages}',
           '\\begin{center}',
           '\\begin{tabular}{l c}',
           '\\toprule',
           'Search terms & N \\\\',
           '\\midrule')
# bottom of latex table
tabBot<-c('\\bottomrule',
           '\\end{tabular}\\\\',
           '\\end{center}',
           '\\end{scriptsize}',
           '\\label{tab:a4}',
           '\\noindent Google searches in the 30 seconds prior to exposure to a webpage classified as not skeptical about the safety and efficacy of vaccines (must be among the three most recently visited webpages).\\\\',
           '\\end{table}')

# combine parts together
(tabFin<-c(tabTop,tabMain,tabBot))
# save to file
writeLines(tabFin,'TableA4.tex')

## Table A5

# get number of times each search term led to a vaccine skeptical page
AntiVaxSearches<-FinDT[code==1,list(search_term,N)]
AntiVaxSearches[,search_term:=gsub('%3a',':',search_term,fixed=T)]
AntiVaxSearches[,search_term:=gsub('%20',' ',search_term,fixed=T)]

# order from most to least
setorder(AntiVaxSearches,-N)
# view table
AntiVaxSearches

# convert to latex table
(tabMain<-apply(AntiVaxSearches,1,function(x) paste(x,collapse=' & ')))
(tabMain<-paste0(tabMain,' \\\\'))

# top of table
tabTop<-c('\\begin{table}[!p]',
          '\\caption{Google searches immediately prior to exposure to vaccine-skeptical webpages}',
          '\\begin{center}',
          '\\begin{tabular}{l c}',
          '\\toprule',
          'Search terms & N \\\\',
          '\\midrule')
# bottom of table
tabBot<-c('\\bottomrule',
           '\\end{tabular}\\\\',
           '\\end{center}',
           '\\noindent Google searches in the 30 seconds prior to exposure to a webpage classified as skeptical about the safety and efficacy of vaccines (must be among the three most recently visited webpages).\\\\',
           '\\label{tab:a5}',
           '\\end{table}')
# combine parts of table
(tabFin<-c(tabTop,tabMain,tabBot))
# save to file
writeLines(tabFin,'TableA5.tex')
